package com.chongba.supplier.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.chongba.entity.Constants;
import com.chongba.entity.order.Result;
import com.chongba.recharge.RechargeRequest;
import com.chongba.recharge.RechargeResponse;
import com.chongba.supplier.conf.SupplierConfig;
import com.chongba.supplier.inf.SupplierService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.annotation.PostConstruct;

@Slf4j
@Service
public class SupplierServiceImpl implements SupplierService {

    @Autowired
    private SupplierConfig supplierConfig;
    @Autowired
    private RestTemplate restTemplate;

    @PostConstruct
    public void init(){
        System.out.println("加载到的配置如下:"+supplierConfig.getApis());
    }

    @Override
    public void recharge(RechargeRequest rechargeRequest) {
        Result<RechargeResponse> result = doDispatchSupplier(rechargeRequest);
        if(result !=null){
        }
    }
    /**
     * 对接逻辑分发
     * @param rechargeRequest
     */
    private Result<RechargeResponse> doDispatchSupplier(RechargeRequest rechargeRequest) {
        //设置供应商的调用地址:
        String url = supplierConfig.getApis().get(rechargeRequest.getSupply());
        rechargeRequest.setRechargeUrl(url);

        //根据需要对接的供应商的编号确定不同的对接方式---不同的api需要传递的参数类型和参数名称等各不相同
        if(Constants.juheapi.equals(rechargeRequest.getSupply())){
            //对接聚合
            return  doPostJuhe(rechargeRequest);
        }else if(Constants.jisuapi.equals(rechargeRequest.getSupply())) {
            //对接极速
            return  doPostJisu(rechargeRequest);
        }
        return null;
    }
    private Result<RechargeResponse> doPostJuhe(RechargeRequest rechargeRequest) {
        //聚合要求传递的是json格式的数据
        //创建并设置请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        //创建请求实体
        HttpEntity httpEntity = new HttpEntity(JSON.toJSONString(rechargeRequest),headers);
        //发送请求
        ResponseEntity<String> responseEntity = restTemplate.postForEntity(rechargeRequest.getRechargeUrl(), httpEntity, String.class);
        //获得结果
        /*String body = responseEntity.getBody();// Result<RechargeResponse>
        Result result = JSON.parseObject(body, Result.class);//因为泛型的问题可能会导致出现问题
        System.out.println(body);*/
        Result<RechargeResponse> result = JSON.parseObject(responseEntity.getBody(), new TypeReference<Result<RechargeResponse>>(){});
        return result;
    }

    // 对接极速
    private Result<RechargeResponse> doPostJisu(RechargeRequest rechargeRequest) {
        return null;
    }
}
